
import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86187
 * Date: 2022-10-17
 * Time: 10:11
 */
public class UdpEchoClient {
    private DatagramSocket socket = null;

    private final String serveIp;
    private final int port;

    public UdpEchoClient(String serveIp, int port) throws SocketException {
        socket = new DatagramSocket();
        this.serveIp = serveIp;
        this.port = port;
    }

    // 启动客户端.
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while(true) {
            // 1. 从控制台读入客户端的请求
            System.out.print("客户端请求-> ");
            String request = scanner.next();
            // 2. 将请求发送给服务器 (要明确服务器的IP和端口号)
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(this.serveIp),this.port);
            socket.send(requestPacket);

            // 3. 从服务器读取响应, 并解析   byte[4096]用于存储响应数据
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());

            // 4. 将响应打印到控制台
            System.out.print("服务器响应-> ");
            System.out.println(response);
            System.out.println();

        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
